<template>
	<view class="tn-safe-area-inset-bottom">

		<!-- 顶部自定义导航 -->
		<tn-nav-bar alpha customBack fixed>
			<view slot="back" class='tn-custom-nav-bar__back' @click="goBack">
				<text class='icon tn-icon-left'></text>
				<text class='icon tn-icon-home-capsule-fill'></text>
			</view>
		</tn-nav-bar>

		<view :style="{paddingTop: vuex_custom_bar_height + 'px'}" class="box">
			<button class="avatar-wrapper-button" open-type="chooseAvatar" @chooseavatar="getUseInfo">
				<image v-if="avatar" :src="avatar" class="avatar"></image>
				<tn-avatar v-else icon="my-job-fill" size="xl"></tn-avatar>
				<!--      <text  v-else class="tn-icon-my-job-fill"></text>-->
			</button>
			<tn-form ref="form" :errorType="['message','border-bottom']" :model="form" labelWidth="180">
				<tn-form-item :required="true" label="昵称" leftIcon="identity" prop="nickname">
					<tn-input v-model="form.nickname" placeholder="请输入昵称" type="nickname"></tn-input>
				</tn-form-item>
				<tn-form-item :required="true" label="手机号" leftIcon="phone" prop="phoneNumber">
					<tn-input v-model="form.phoneNumber" placeholder="请输入手机号" type="tel"></tn-input>
				</tn-form-item>
				<tn-form-item label="微信号" leftIcon="wechat" prop="wechatId">
					<tn-input v-model="form.wechatId" placeholder="请输入微信号" type="text"></tn-input>
				</tn-form-item>
				<tn-form-item label="邀请码" leftIcon="qr-code" prop="inviteCode">
					<tn-input v-model="form.inviteCode" placeholder="请输入邀请码" type="text"
						:disabled="inviteDisabled"></tn-input>
				</tn-form-item>
			</tn-form>
			<view style="height: 100rpx"></view>
			<tn-button :shadow="true" backgroundColor="tn-main-gradient-indigo" class="submit-form" height="100rpx"
				width="100%" @click="submitForm">
        {{type === 'update' ? "修改" : "提交"}}
			</tn-button>
		</view>
	</view>
</template>

<script>
	import {
		addUserInfo
	} from "@/api/login";
	import {
		uploadToOSS
	} from "@/api/oss";
	import template_page_mixin from '@/libs/mixin/template_page_mixin.js'


	export default {
		mixins: [template_page_mixin],
		data: () => {
			return {
				avatar: '',
				inviteDisabled: false,
				form: {
					nickname: '',
					phoneNumber: '',
					wechatId: '',
					inviteCode: ''
				},
				rules: {
					nickname: [{
						required: true,
						message: '请输入昵称',
						trigger: 'blur'
					}, ],
					phoneNumber: [{
							required: true,
							message: '请输入手机号',
							trigger: 'blur'
						},
						{
							pattern: /^1[3-9]\d{9}$/,
							message: '手机号格式不正确',
							trigger: 'blur'
						}
					],
				},
        type: "", // 是否是修改
			}
		},
		methods: {
			async getUseInfo(data) {
				this.avatar = data.detail.avatarUrl
				try {
				const avatarRes = await uploadToOSS(this.avatar, 'avatar')
				if (avatarRes.code === 200) {
					this.avatar = avatarRes.data.url
				}
				} catch (e) {
				console.log(e)
				}
			},
			async submitForm() {
				await this.$refs.form.validate(async valid => {
					if (valid) {
						if (this.avatar == '') {
							uni.showToast({
								title: "请上传头像",
								duration: 1500,
								icon: 'error'
							});
							return;
						}
            const params = {
              ...this.form,
              headSculpture: this.avatar
            }
            const res = await addUserInfo(params)
            if (res.code === 200) {
              if(this.type === 'update') {
                let pages = getCurrentPages();
                let prevPage = pages[pages.length - 2]; //上一页页面实例
                uni.navigateBack({
                  delta: 1,
                  success: () => {
                    prevPage.onLoad({index: 0}); // 执行上一页的onLoad函数
                    this.$store.dispatch('getUserInfo').then(res => {});
                  }
                })
               return
              }
              this.goHome()
            } else if (res.code === 100001) {
              console.log(123)
              uni.showToast({
                title: res.msg,
                duration: 1500,
                icon: 'error'
              });
            } else {
              uni.showToast({
                title: "注册失败",
                duration: 1500,
                icon: 'error'
              });
            }

					} else {
						return false
					}
				})
			},
		},
		async onLoad(param) {
			await this.$onLaunched;
			if (this.$store.getters.getUserInfo) {
        if(param.type === "update") {
          const userInfo = this.$store.getters.getUserInfo;
          this.form.nickname = userInfo.nickname;
          this.form.phoneNumber = userInfo.phoneNumber;
          this.form.inviteCode = userInfo.inviteCode;
          this.form.wechatId = userInfo.wechatId;
          this.avatar = userInfo.headSculpture;
          this.type = "update";
          if(userInfo.inviteCode) {
            this.inviteDisabled = true;
          }
        } else {
          uni.reLaunch({
          	url: '/pages/index/index'
          })
        }
			}
			if (param.shareCode) {
				this.form.inviteCode = param.shareCode
				this.inviteDisabled = true
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
	}
</script>

<style lang="scss">
	/* 胶囊*/
	.tn-custom-nav-bar__back {
		width: 100%;
		height: 100%;
		position: relative;
		display: flex;
		justify-content: space-evenly;
		align-items: center;
		box-sizing: border-box;
		background-color: rgba(0, 0, 0, 0.15);
		border-radius: 1000rpx;
		border: 1rpx solid rgba(255, 255, 255, 0.5);
		color: #FFFFFF;
		font-size: 18px;

		.icon {
			display: block;
			flex: 1;
			margin: auto;
			text-align: center;
		}

		&:before {
			content: " ";
			width: 1rpx;
			height: 110%;
			position: absolute;
			top: 22.5%;
			left: 0;
			right: 0;
			margin: auto;
			transform: scale(0.5);
			transform-origin: 0 0;
			pointer-events: none;
			box-sizing: border-box;
			opacity: 0.7;
			background-color: #FFFFFF;
		}
	}

	.box {
		padding: 0 20rpx;

		.avatar-wrapper-button {
			background-color: transparent;
			margin-top: 60rpx;

			&:after {
				border: none;
			}

			.avatar {
				width: 100rpx;
				height: 100rpx;
			}

			.empty-avatar {
				width: 100rpx;
				height: 100rpx;
			}
		}

		.submit-form {
			margin-top: 80rpx;
		}

	}
</style>